﻿using System.Collections.Generic;
using System.Linq;
using QuailServices;

namespace Quail
{
    /// <summary>
    /// Class to manage access to the remote control host pool
    /// </summary>
    public static class RemoteControlPool
    {
        /// <summary>
        /// Gets the next available remote control host from the pool
        /// </summary>
        /// <param name="testname">The testname.</param>
        /// <param name="capabilities">The capabilities needed for the test.</param>
        /// <returns>A RemoteControlHost or null if no acceptable host was found</returns>
        public static RemoteControlHost GetRemoteControlHost(string testname, params string[] capabilities)
        {
            using (var service = QuailDataServiceFactory.CreateClient())
            {
                var newhost = service.GetNextRemoteControlHost(testname, capabilities);

                return (newhost == null || !newhost.HostPort.HasValue || !newhost.HostKey.HasValue)
                           ? null
                           : new RemoteControlHost(newhost);
            }
        }

        /// <summary>
        /// Removes a non-responsive remote control host from the pool
        /// </summary>
        /// <param name="host">the remote control host</param>
        public static void RemoveRemoteControlHostFromPool(RemoteControlHost host)
        {
            using (var service = QuailDataServiceFactory.CreateClient())
            {
                service.ConfigureRemoteControl(host.Host, host.Port, false);
            }
        }

        /// <summary>
        /// Adds an array of capabilities into the system
        /// </summary>
        /// <param name="capabilities">The capabilities to add</param>
        public static void AddCapabilities(IEnumerable<Quail.RemoteControlCapability> capabilities)
        {
            using (var service = QuailDataServiceFactory.CreateClient())
            {
                var newcaps = capabilities.Select(cap => new QuailServices.QuailDataServiceReference.RemoteControlCapability
                                               {
                                                   Description = cap.Description,
                                                   RemoteControlCapabilityCode = cap.Code
                                               }).ToArray();

                service.AddRemoteControlCapabilities(newcaps);
            }
        }
    }
}
